package com.kld.shop.controller.admin;

import com.github.pagehelper.PageInfo;
import com.kld.common.framework.dto.ResultMsg;
import com.kld.common.framework.global.EnumList;
import com.kld.common.framework.global.Global;
import com.kld.common.framework.page.PageInfoResult;
import com.kld.common.redis.JedisManager;
import com.kld.common.util.DateUtil;
import com.kld.common.util.DateUtils;
import com.kld.common.util.FileUpload;
import com.kld.promotion.api.*;
import com.kld.promotion.po.ActProRel;
import com.kld.promotion.po.Actitem;
import com.kld.promotion.po.Activity;
import com.kld.promotion.po.Actorder;
import com.kld.shop.controller.base.BaseController;
import com.kld.sys.api.ImgsService;
import com.kld.sys.po.Imgs;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Dan on 2015/10/29.
 */
@Controller
@RequestMapping("/admin/act")
public class ActivityController extends BaseController {

    @Autowired
    private IActivityService activityService;
    @Autowired
    private IActItemService actItemService;
    @Autowired
    private IActOrderService actOrderService;
    @Autowired
    private IActProRelService actProRelService;
//    @Autowired
//    private IProCateGoryService categoryService;
    //IProCateGoryService 这个还没完成
    @Autowired
    private ImgsService imgsService;



    @RequestMapping(value = "actList")
    public String actList() {
        return "/admin/act/actList";
    }

    @RequestMapping(value = "monthActList")
    public String monthActList() {

        return "/admin/act/monthActList";
    }

    @RequestMapping(value = "proActTradeList")
    public String proActDetailList() {

        return "/admin/act/proActTradeList";
    }

    /* *
      * 活动商品补贴明细
      * @return*/
    @ResponseBody()
    @RequestMapping(value = "getProActTradeList", method = RequestMethod.GET)
    public ResultMsg getProActTradeList() {
        // TODO: 2016/3/28  getActProTradeList 方法查询数据库的语句还有问题
        ResultMsg rmsg = new ResultMsg();
        Map<String, Object> map = getProActTradeQueryInfo(request); //获取查询条件
        List<ActProRel> actProList = actProRelService.getActProTradeList(map);
        rmsg.setResult(true);
        rmsg.setRows(actProList);
        rmsg.setTotal(actProList.size());
        return rmsg;
    }


    @RequestMapping(value = "exportProActTradeExcel", method = RequestMethod.GET)
    public void exportProActTradeExcel() {
        Map<String, Object> map = getProActTradeQueryInfo(request);
        List<ActProRel> list = actProRelService.getActProTradeList(map);
        String excelPath = "/Autowireds/doctemplate/tpl_proActTradeDetail.xls";
        String root = request.getSession().getServletContext().getRealPath("/");
        String fileName = null;
        response.setCharacterEncoding("utf-8");
        try {
            response.setContentType("application/vnd.ms-excel; charset=ISO8859-1");
            InputStream is = new FileInputStream(root + excelPath);
            HSSFWorkbook wb = new HSSFWorkbook(is);
            HSSFSheet sheet = wb.getSheetAt(0);
            HSSFRow row = sheet.getRow(1);
            HSSFCell cell = row.getCell(0);
            int maxcolnum = 24, minrownum = 1, flag = minrownum;
            ActProRel sActProRel = new ActProRel();
            sActProRel.setSalenum(BigDecimal.valueOf(0));
            sActProRel.setTradepoints(BigDecimal.valueOf(0));
            sActProRel.setTradeamount(BigDecimal.valueOf(0));
            sActProRel.setTotalmctprice(BigDecimal.valueOf(0));
            sActProRel.setTotalprofit(BigDecimal.valueOf(0));
            sActProRel.setTradediscountpoints(BigDecimal.valueOf(0));
            sActProRel.setTradediscount(BigDecimal.valueOf(0));
            sActProRel.setDeliverednum(BigDecimal.valueOf(0));
            sActProRel.setDelivereddiscountpoints(BigDecimal.valueOf(0));
            sActProRel.setDelivereddiscount(BigDecimal.valueOf(0));
            Map<String, List<ActProRel>> resultMap = new HashMap<String, List<ActProRel>>();
            for (ActProRel apr : list) {
                HSSFRow newRow = sheet.createRow(flag);
                for (int j = 0; j < maxcolnum; j++) {
                    newRow.createCell(j).setCellStyle(cell.getCellStyle());
                }
                String key = apr.getActid() + "_" + apr.getProductid() + "_" + apr.getMctprice() + "_" + apr.getActprice();
                if (!resultMap.containsKey(key)) {
                    resultMap.put(key, new ArrayList<ActProRel>());
                }
                List<ActProRel> value = resultMap.get(key);
                value.add(apr);
                resultMap.put(key, value);
                sActProRel.setSalenum(BigDecimal.valueOf(sActProRel.getSalenum().intValue() + apr.getSalenum().intValue()));
                sActProRel.setTradepoints(BigDecimal.valueOf(sActProRel.getTradepoints().intValue() + apr.getTradepoints().intValue()));
                sActProRel.setTradeamount(BigDecimal.valueOf(sActProRel.getTradeamount().doubleValue() + apr.getTradeamount().doubleValue()));
                sActProRel.setTotalmctprice(BigDecimal.valueOf(sActProRel.getTotalmctprice().doubleValue()+apr.getTotalmctprice().doubleValue()));
                sActProRel.setTotalprofit(BigDecimal.valueOf(sActProRel.getTotalprofit().doubleValue()+apr.getTotalprofit().doubleValue()));
                sActProRel.setTradediscountpoints(BigDecimal.valueOf(sActProRel.getTradediscountpoints().intValue() + apr.getTradediscountpoints().intValue()));
                sActProRel.setTradediscount(BigDecimal.valueOf(sActProRel.getTradediscount().doubleValue() + apr.getTradediscount().doubleValue()));
                sActProRel.setDeliverednum(BigDecimal.valueOf(sActProRel.getDeliverednum().intValue() + apr.getDeliverednum().intValue()));
                sActProRel.setDelivereddiscountpoints(BigDecimal.valueOf(sActProRel.getDelivereddiscountpoints().intValue() + apr.getDelivereddiscountpoints().intValue()));
                sActProRel.setDelivereddiscount(BigDecimal.valueOf(sActProRel.getDelivereddiscount().doubleValue() + apr.getDelivereddiscount().doubleValue()));
                flag++;
            }
            int currrownum = minrownum;
            for (String key : resultMap.keySet()) {
                List<ActProRel> listvalue = resultMap.get(key);
                int lastrownum = currrownum + ((listvalue != null && listvalue.size() > 0) ? listvalue.size() - 1 : 0);  //合并单元格最后行号
                sheet.addMergedRegion(new CellRangeAddress(currrownum, lastrownum, 0, 0));
                sheet.addMergedRegion(new CellRangeAddress(currrownum, lastrownum, 1, 1));
                sheet.addMergedRegion(new CellRangeAddress(currrownum, lastrownum, 2, 2));
                sheet.addMergedRegion(new CellRangeAddress(currrownum, lastrownum, 3, 3));
                sheet.addMergedRegion(new CellRangeAddress(currrownum, lastrownum, 4, 4));
                sheet.addMergedRegion(new CellRangeAddress(currrownum, lastrownum, 5, 5));
                int colnum = 0;
                ActProRel apr0 = listvalue.get(0);
                sheet.getRow(currrownum).getCell(colnum++).setCellValue(apr0.getActid().intValue());
                sheet.getRow(currrownum).getCell(colnum++).setCellValue(apr0.getActtitle());
                sheet.getRow(currrownum).getCell(colnum++).setCellValue(apr0.getProductname());
                sheet.getRow(currrownum).getCell(colnum++).setCellValue(apr0.getMctname());
                sheet.getRow(currrownum).getCell(colnum++).setCellValue(apr0.getThirdcode());
                sheet.getRow(currrownum).getCell(colnum++).setCellValue(apr0.getProductcode());
                for (ActProRel apr : listvalue) {

                    int colnum2 = colnum;
                    HSSFRow currrow = sheet.getRow(currrownum++);
                    currrow.getCell(colnum2++).setCellValue(apr.getPoints() == null ? 0 : apr.getPoints().intValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getActprice() == null ? 0 : apr.getActprice().doubleValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getSalenum() == null ? 0 : apr.getSalenum().intValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getTradepoints() == null ? 0 : apr.getTradepoints().intValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getTradeamount() == null ? 0 : apr.getTradeamount().doubleValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getMctprice() == null ? 0 : apr.getMctprice().doubleValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getTotalmctprice() == null ? 0 : apr.getTotalmctprice().doubleValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getOriginpoints() == null ? 0 : apr.getOriginpoints().intValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getOriginselfprice() == null ? 0 : apr.getOriginselfprice().doubleValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getProfit() == null ? 0 : apr.getProfit().doubleValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getTotalprofit() == null ? 0 : apr.getTotalprofit().doubleValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getDiscountpoints() == null ? 0 : apr.getDiscountpoints().intValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getDiscount() == null ? 0 : apr.getDiscount().doubleValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getTradediscountpoints() == null ? 0 : apr.getTradediscountpoints().intValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getTradediscount() == null ? 0 : apr.getTradediscount().doubleValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getDeliverednum() == null ? 0 : apr.getDeliverednum().intValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getDelivereddiscountpoints() == null ? 0 : apr.getDelivereddiscountpoints().intValue());
                    currrow.getCell(colnum2++).setCellValue(apr.getDelivereddiscount() == null ? 0 : apr.getDelivereddiscount().doubleValue());
                }
            }

            HSSFRow sumrow = sheet.createRow(currrownum++);
            for (int j = 0; j < maxcolnum; j++) {
                sumrow.createCell(j).setCellStyle(cell.getCellStyle());
                sumrow.getCell(j).setCellValue("--");
            }
            sumrow.getCell(0).setCellValue("合计");
            sumrow.getCell(8).setCellValue(sActProRel.getSalenum().intValue());
            sumrow.getCell(9).setCellValue(sActProRel.getTradepoints().intValue());
            sumrow.getCell(10).setCellValue(sActProRel.getTradeamount().intValue());
            sumrow.getCell(12).setCellValue(sActProRel.getTotalmctprice().doubleValue());
            sumrow.getCell(16).setCellValue(sActProRel.getTotalprofit().doubleValue());
            sumrow.getCell(19).setCellValue(sActProRel.getTradediscountpoints().intValue());
            sumrow.getCell(20).setCellValue(sActProRel.getTradediscount().doubleValue());
            sumrow.getCell(21).setCellValue(sActProRel.getDeliverednum().intValue());
            sumrow.getCell(22).setCellValue(sActProRel.getDelivereddiscountpoints().intValue());
            sumrow.getCell(23).setCellValue(sActProRel.getDelivereddiscount().doubleValue());
            fileName = new String(("活动商品补贴明细").getBytes("gb2312"), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    fileName + DateUtils.formatDate( DateUtils.getDate()) + ".xls");
            OutputStream ouputStream = response.getOutputStream();
            wb.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
//            poi 3.9没有close方法
//            if (wb != null) {
//                wb.close();
//            }
        } catch (Exception ex) {
            String opname = "活动商品补贴明细";
            BufferedOutputStream bos = null;
            logger.error("导出" + opname + "异常:" + ex.getMessage(), ex);
            try {
                response.setContentType("text/plain");
                fileName = new String((opname + "导出失败").getBytes("gb2312"), "ISO8859-1");
                bos = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[2048];
                if (ex != null) {
                    buff = (ex.toString() + "==> 异常行号:" + ex.getStackTrace()[0].getLineNumber()).getBytes();
                }
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        fileName + DateUtils.formatDate(DateUtils.getDate()) + ".txt");
                bos.write(buff);
                bos.flush();
                if (bos != null) {
                    bos.close();
                }
            } catch (Exception e) {
                logger.error("导出" + opname + "异常失败:" + e.getMessage(), e);
            }

        }
        return;
    }

    private Map<String, Object> getProActTradeQueryInfo(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
//        String sActid = request.getParameter("sActid");
        String sActids = request.getParameter("sActids");
        String sProName = request.getParameter("sProName");
        String sThirdcode = request.getParameter("sThirdcode");
        String sCode = request.getParameter("sCode");
        String sFromDate = request.getParameter("sFromDate");
        String sToDate = request.getParameter("sToDate");
        String sort = request.getParameter("sort");
        String order = request.getParameter("order");
        if (!"1".equals(getUserOuLevel())) {
            map.put("oucode", getUserOuCode());
        }

        if(StringUtils.isNotBlank(sActids)){
            String[] idstrs = sActids.split(",");
            List<Integer> actidList = new ArrayList<Integer>();
            for(String idstr:idstrs){
                actidList.add(Integer.parseInt(idstr));
            }
            if(actidList.size()>0){
                map.put("actids",actidList);
            }
        }

        if (StringUtils.isNotBlank(sProName)) {
            map.put("productname", sProName);
        }
        if (StringUtils.isNotBlank(sThirdcode)) {
            map.put("thirdcode", sThirdcode);
        }
        if (StringUtils.isNotBlank(sCode)) {
            map.put("productcode", sCode);
        }
        if (StringUtils.isNotBlank(sFromDate)) {
            map.put("fromdate", DateUtils.parseDate(sFromDate));
        }
        if (StringUtils.isNotBlank(sToDate)) {
            map.put("todate", DateUtils.parseDate(sToDate));
        }
        if (StringUtils.isBlank(sort)) {
            sort = "s.actid";
        }
        if (StringUtils.isBlank(order)) {
            order = "desc";
        }
        map.put("sort", sort);
        map.put("order", order);

        return map;
    }

    /* *
      * 获取促销活动商品列表
      * @return*/
    @ResponseBody()
    @RequestMapping(value = "getActProList", method = RequestMethod.GET)
    public ResultMsg getActProList() {
        ResultMsg rmsg = new ResultMsg();
        String curractid = request.getParameter("actid");
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(curractid)) {
            map.put("actid", Integer.parseInt(curractid));
        }
        PageInfo pageInfo = null;
        try {
            pageInfo = actProRelService.getActProList(map,getPageNum(),getPageSize());
        }catch (Exception e){
            logger.error("获取促销活动商品列表"+e.getMessage(),e);
            e.printStackTrace();
        }
        return PageInfoResult.PageInfoMsg(pageInfo);
    }

    /* *
      * 获取促销活动商品列表
      * @return*/
    @ResponseBody()
    @RequestMapping(value = "getProList", method = RequestMethod.GET)
    public ResultMsg getProList() {
        ResultMsg rmsg = new ResultMsg();
        return rmsg;
        // TODO: 2016/3/28 商品相关的。
//        String productname = request.getParameter("name");
//        String thirdcodeStr = request.getParameter("sThirdCode");
//        String productcode = request.getParameter("sCode");
//        String mctcode = request.getParameter("sMctCode");
//        String limittype = request.getParameter("sLimitType");
//        String minlimit = request.getParameter("sMinLimit");
//        String maxlimit = request.getParameter("sMaxLimit");
//        String curractid = request.getParameter("curractid");
//        List<String> categorys = new ArrayList<String>();
//        String catecode = request.getParameter("sCatecode");
//
//
//        Map<String, Object> map = new HashMap<String, Object>();
//        if (StringUtils.isNotBlank(productname)) {
//            map.put("productname", productname);
//        }
//        if (StringUtils.isNotBlank(thirdcodeStr)) {
//            List<String> thirdcode = Arrays.asList(thirdcodeStr.split(","));
//            map.put("thirdcode", thirdcode);
//            //变成list
//        }
//        if (StringUtils.isNotBlank(productcode)) {
//            map.put("productcode", productcode);
//        }
//        if (StringUtils.isNotBlank(mctcode)) {
//            map.put("mctcode", mctcode);
//        }
//        if (StringUtils.isNotBlank(limittype)) {
//            map.put("limittype", limittype);
//        }
//        if (StringUtils.isNotBlank(minlimit)) {
//            map.put("minlimit", minlimit);
//        }
//        if (StringUtils.isNotBlank(maxlimit)) {
//            map.put("maxlimit", maxlimit);
//        }
//        if (StringUtils.isNotBlank(curractid)) {
//            map.put("curractid", curractid);
//        }
//        if (StringUtils.isNotBlank(catecode)) {
//            Map<String, Object> cmap = new HashMap<String, Object>();
//            ProCateGory category = productService.selectCategoryByCode(catecode);
//            String codes = "";
//
//            if (category != null) {
//                if (category.getCategorylevel().equals(3)) {
//                    categorys.add(category.getCode());
//
//                } else if (category.getCategorylevel() >= 1 && category.getCategorylevel() < 3) {
//                    cmap.put("level", category.getCategorylevel());
//                    cmap.put("code", category.getCode());
//                    categorys = categoryService.getCodesByLevelAndPcode(cmap);
//                }
//                map.put("catecodes", categorys);
//            }
//        }
//        if ("1".equals(getUserOuLevel())) {
//
//        } else {
//            map.put("oucode", getUserOuCode());
//        }
//        PageHelper.startPage(getPageNum(), getPageSize());
//        List<Product> actProList = actProRelService.getProList(map);
//        PageInfo pageInfo = new PageInfo(actProList);
//        return PageInfoResult.PageInfoMsg(pageInfo);

    }

    /* *
      * 删除促销活动商品
      * @return
      * */
    @ResponseBody()
    @RequestMapping(value = "deleteActPro", method = RequestMethod.POST)
    public ResultMsg deleteActPro(String ids) {
        ResultMsg rmsg = new ResultMsg();
        rmsg = actProRelService.deleteLogic(ids);
        return rmsg;
    }


    /* *
      * 设置商品促销规则
      * @return
      * */
    @ResponseBody()
    @RequestMapping(value = "setActProRule", method = RequestMethod.POST)
    public ResultMsg setActProRule(String idsStr, BigDecimal discountrate, BigDecimal points, BigDecimal num) {
        ResultMsg rmsg = new ResultMsg();
        if (discountrate == null) {
            discountrate = BigDecimal.valueOf(0);
        }
        if (points == null) {
            points = BigDecimal.valueOf(0);
        }
        if (num == null) {
            num = BigDecimal.valueOf(0);
        }
        try {
            rmsg = actProRelService.setActProRule(idsStr, discountrate, points, num);
        } catch (Exception ex) {
            logger.error("设置活动商品规则异常:" + ex.getMessage(), ex);
            rmsg.setResult(false);
            rmsg.setMsg(ex.getMessage());
        }
        return rmsg;
    }


    /* *
      * 设置特推权重
      * @return
      * */
    @ResponseBody()
    @RequestMapping(value = "setActProWeight", method = RequestMethod.GET)
    public ResultMsg setActProRule() {
        String idStr = request.getParameter("id");
        String weightStr = request.getParameter("weight");
        Integer id = 0;
        BigDecimal weight = BigDecimal.valueOf(0);
        ResultMsg rmsg = new ResultMsg();

        if (StringUtils.isNotBlank(idStr)) {
            id = Integer.parseInt(idStr);
        }
        if (StringUtils.isNotBlank(weightStr)) {
            weight = new BigDecimal(weightStr);
        }
        try {
            rmsg = actProRelService.setActProWeight(id, weight);
        } catch (Exception ex) {
            logger.error("设置活动商品规则异常:" + ex.getMessage(), ex);
            rmsg.setResult(false);
            rmsg.setMsg(ex.getMessage());
        }
        return rmsg;
    }


    /* *
      * 取消特推
      * @return
      * */
    @ResponseBody()
    @RequestMapping(value = "cancelActProWeight", method = RequestMethod.POST)
    public ResultMsg cancelActProWeight(String idsStr) {
        ResultMsg rmsg = new ResultMsg();

        List<Integer> ids = new ArrayList<Integer>();
        try {
            String[] idsArr = idsStr.split(",");
            for (String idStr : idsArr) {
                ids.add(Integer.parseInt(idStr));
            }
        } catch (Exception ex) {
            logger.error("取消特推商品失败！参数有误：" + idsStr, ex);
            rmsg.setResult(false);
            rmsg.setMsg("参数有误");
        }
        try {
            rmsg = actProRelService.cancelActProWeight(ids);
        } catch (Exception ex) {
            logger.error("设置活动商品规则异常:" + ex.getMessage(), ex);
            rmsg.setResult(false);
            rmsg.setMsg(ex.getMessage());
        }
        return rmsg;
    }


    /**
     * 添加活动商品
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "addActPro", method = RequestMethod.POST)
    public ResultMsg addActPro(BigDecimal actid, String proidsStr) {
        ResultMsg rmsg = new ResultMsg();
        List<Integer> proids = new ArrayList<Integer>();
        String username = getUserName();
        try {
            String[] proidArr = proidsStr.split(",");
            for (String id : proidArr) {
                proids.add(Integer.parseInt(id));
            }
        } catch (Exception ex) {
            logger.error("添加活动商品失败：" + ex.getMessage(), ex);
            rmsg.setResult(false);
            rmsg.setMsg("活动商品参数有误");
            return rmsg;
        }
        if (proids.size() == 0) {
            rmsg.setResult(false);
            rmsg.setMsg("未选择商品");
            return rmsg;
        }
        try {
            rmsg = actProRelService.insertWithTrans(actid, proids, username);
        } catch (Exception ex) {
            logger.error("新增活动商品异常：" + ex.getMessage(), ex);
            rmsg.setResult(false);
            rmsg.setMsg(ex.getMessage());
        }

        return rmsg;
    }

    /**
     * 获取活动列表
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "getActList", method = RequestMethod.GET)
    public ResultMsg getActList() {
        Map<String, Object> map = new HashMap<String, Object>();
        //region 查询条件
        String sTitle = request.getParameter("sTitle");
        String sState = request.getParameter("sState");
        String sType = request.getParameter("sType");
        String sFromDate = request.getParameter("sFromDate");
        String sToDate = request.getParameter("sToDate");
        if (StringUtils.isNotBlank(sTitle)) {
            map.put("title", sTitle);
        }
        if (StringUtils.isNotBlank(sState) && !("0".equals(sState))) {
            map.put("state", sState);
        }
        if (StringUtils.isNotBlank(sType) && !("0".equals(sType))) {
            map.put("type", sType);
        }
        if (StringUtils.isNotBlank(sFromDate)) {
            map.put("fromdate", DateUtils.parseDate(sFromDate));
        }
        if (StringUtils.isNotBlank(sToDate)) {
//            map.put("todate", DateUtils.parseDate("yyyy-MM-dd", DateUtils.formatDate(DateUtils.addDays(DateUtils.parseDate(sToDate), 1))));
            map.put("todate", DateUtils.plusOneDay(DateUtils.parseDate(sToDate)));
        }
        if ("1".equals(getUserOuLevel())) {

        } else {
            map.put("oucode", getUserOuCode());
        }
        //endregion
        PageInfo pageInfo = null;
        try {
            pageInfo = activityService.getActList(map,getPageNum(),getPageSize());
            for (Object  o: pageInfo.getList()) {
                Activity act = (Activity)o;
                act.setActitems(actItemService.getActItemByActId(act.getId()));
            }
        }catch (Exception e){
            logger.error("获取获奖名单列表错误"+e.getMessage(),e);
            e.printStackTrace();
        }
        return PageInfoResult.PageInfoMsg(pageInfo);
    }

    /**
     * 获取活动列表
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "getActs", method = RequestMethod.POST)
    public List<Activity> getActs() {
        Map<String, Object> map = new HashMap<String, Object>();
        //region 查询条件

        String type = request.getParameter("type");
        String q = request.getParameter("q");
        if (!"1".equals(getUserOuLevel())) {
            map.put("oucode", getUserOuCode());
            map.put("oucode","1");
        }
        if (StringUtils.isNotBlank(q)) {
            map.put("q", q.toUpperCase());
        }
        if (StringUtils.isNotBlank(type)) {
            map.put("type", type);
        }

        //endregion
        List<Activity> list = activityService.getActList(map);

        return list;
    }

    /**
     * 添加、编辑活动
     *
     * @param activity
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "editAct", method = RequestMethod.POST)
    public ResultMsg editAct(Activity activity) {
        ResultMsg rmsg = new ResultMsg();
        if (activity.getId() != null && activity.getId().intValue() > 0) {
            //region 编辑活动
            int r = activityService.updateByPrimaryKeySelective(activity);
            if (r > 0) {
                rmsg.setResult(true);
                rmsg.setMsg("编辑成功");
//                cacheService.delFrontCache(Global.INDEX_JIFENPRIZE);
            } else {
                rmsg.setResult(false);
                rmsg.setMsg("编辑失败");
            }
            //endregion
        } else {
            //region 添加活动
           /* boolean titleUsed = activityService.checkTitleIfUsed(activity.getTitle());
            if(titleUsed){
                rmsg.setResult(false);
                rmsg.setMsg("活动主题已存在");
                return rmsg;
            }*/
            activity.setOucode(getUserOuCode());
            activity.setPid(BigDecimal.valueOf(0));
            activity.setCreator(getUserDetails().getUsername());
            activity.setState(BigDecimal.valueOf(EnumList.ActState.UnPublish.value));
            int r = activityService.insertSelective(activity);
            if (r > 0) {
                rmsg.setResult(true);
                rmsg.setMsg("添加成功");
//                cacheService.delFrontCache(Global.INDEX_JIFENPRIZE);

            } else {
                rmsg.setResult(false);
                rmsg.setMsg("添加失败");
            }
            //endregion
        }
        //清除前台缓存信息
        if (rmsg.getResult()) {
            //更新图片
            if (StringUtils.isNotBlank(activity.getWebTitleimg())) {
                Imgs img = imgsService.getPrimaryImg(activity.getId(), EnumList.ImgClsId.WebTitleimg.value);
                if (img == null) {
                    img = new Imgs();
                    img.setModifytime(new Date());
                    img.setBsnsid(activity.getId());
                    img.setCreator(getUserName());
                    img.setCreatetime(new Date());
                    img.setOucode(activity.getOucode());
                    img.setIsdel(new BigDecimal(0));
                    img.setIsprimary(new BigDecimal(1));
                    img.setClsid(new BigDecimal(EnumList.ImgClsId.WebTitleimg.value));
                    img.setPicurl(activity.getWebTitleimg());
                    imgsService.insertSelective(img);
                } else {
                    img.setPicurl(activity.getWebTitleimg());
                    imgsService.updateByPrimaryKeySelective(img);
                }

            }
            if (StringUtils.isNotBlank(activity.getWebBackgroundimg())) {

                Imgs img = imgsService.getPrimaryImg(activity.getId(), EnumList.ImgClsId.WebBackgroundimg.value);
                if (img == null) {
                    img = new Imgs();

                    img.setBsnsid(activity.getId());
                    img.setCreator(getUserName());
                    img.setCreatetime(new Date());
                    img.setOucode(activity.getOucode());
                    img.setIsdel(new BigDecimal(0));
                    img.setIsprimary(new BigDecimal(1));
                    img.setClsid(new BigDecimal(EnumList.ImgClsId.WebBackgroundimg.value));
                    img.setPicurl(activity.getWebBackgroundimg());

                    imgsService.insertSelective(img);
                } else {
                    img.setPicurl(activity.getWebBackgroundimg());
                    imgsService.updateByPrimaryKeySelective(img);
                }
            }
            if (StringUtils.isNotBlank(activity.getWxTitleimg())) {
                Imgs img = imgsService.getPrimaryImg(activity.getId(), EnumList.ImgClsId.WxTitleimg.value);
                if (img == null) {
                    img = new Imgs();
                    img.setBsnsid(activity.getId());
                    img.setCreator(getUserName());
                    img.setCreatetime(new Date());
                    img.setOucode(activity.getOucode());
                    img.setIsdel(new BigDecimal(0));
                    img.setIsprimary(new BigDecimal(1));
                    img.setClsid(new BigDecimal(EnumList.ImgClsId.WxTitleimg.value));
                    img.setPicurl(activity.getWxTitleimg());

                    imgsService.insertSelective(img);
                } else {
                    img.setPicurl(activity.getWxTitleimg());

                    imgsService.updateByPrimaryKeySelective(img);
                }
            }
            if (StringUtils.isNotBlank(activity.getWxBackgroundimg())) {
                Imgs img = imgsService.getPrimaryImg(activity.getId(), EnumList.ImgClsId.WxBackgroundimg.value);
                if (img == null) {
                    img = new Imgs();
                    img.setBsnsid(activity.getId());
                    img.setCreator(getUserName());
                    img.setCreatetime(new Date());
                    img.setOucode(activity.getOucode());
                    img.setIsdel(new BigDecimal(0));
                    img.setIsprimary(new BigDecimal(1));
                    img.setClsid(new BigDecimal(EnumList.ImgClsId.WxBackgroundimg.value));
                    img.setPicurl(activity.getWxBackgroundimg());
                    imgsService.insertSelective(img);
                } else {
                    img.setPicurl(activity.getWxBackgroundimg());
                    imgsService.updateByPrimaryKeySelective(img);
                }
            }
            if (StringUtils.isNotBlank(activity.getWebItemBannerimg())) {
                Imgs img = imgsService.getPrimaryImg(activity.getId(), EnumList.ImgClsId.WebItemBannerimg.value);
                if (img == null) {
                    img = new Imgs();
                    img.setBsnsid(activity.getId());
                    img.setCreator(getUserName());
                    img.setCreatetime(new Date());
                    img.setOucode(activity.getOucode());
                    img.setIsdel(new BigDecimal(0));
                    img.setIsprimary(new BigDecimal(1));
                    img.setClsid(new BigDecimal(EnumList.ImgClsId.WebItemBannerimg.value));
                    img.setPicurl(activity.getWebItemBannerimg());
                    imgsService.insertSelective(img);
                } else {
                    img.setPicurl(activity.getWebItemBannerimg());
                    imgsService.updateByPrimaryKeySelective(img);
                }
            }
            if (StringUtils.isNotBlank(activity.getWebItemBackgroundimg())) {
                Imgs img = imgsService.getPrimaryImg(activity.getId(), EnumList.ImgClsId.WebItemBackgroundimg.value);
                if (img == null) {
                    img = new Imgs();
                    img.setBsnsid(activity.getId());
                    img.setCreator(getUserName());
                    img.setCreatetime(new Date());
                    img.setOucode(activity.getOucode());
                    img.setIsdel(new BigDecimal(0));
                    img.setIsprimary(new BigDecimal(1));
                    img.setClsid(new BigDecimal(EnumList.ImgClsId.WebItemBackgroundimg.value));
                    img.setPicurl(activity.getWebItemBackgroundimg());
                    imgsService.insertSelective(img);
                } else {
                    img.setPicurl(activity.getWebItemBackgroundimg());
                    imgsService.updateByPrimaryKeySelective(img);
                }
            }
            if (StringUtils.isNotBlank(activity.getWebItemBackgroundcolor())) {
                Imgs img = imgsService.getPrimaryImg(activity.getId(), EnumList.ImgClsId.WebItemBackgroundcolor.value);
                if (img == null) {
                    img = new Imgs();
                    img.setBsnsid(activity.getId());
                    img.setCreator(getUserName());
                    img.setCreatetime(new Date());
                    img.setOucode(activity.getOucode());
                    img.setIsdel(new BigDecimal(0));
                    img.setIsprimary(new BigDecimal(1));
                    img.setClsid(new BigDecimal(EnumList.ImgClsId.WebItemBackgroundcolor.value));
                    img.setPicurl(activity.getWebItemBackgroundcolor());
                    imgsService.insertSelective(img);
                } else {
                    img.setPicurl(activity.getWebItemBackgroundcolor());
                    imgsService.updateByPrimaryKeySelective(img);
                }
            }
            if (StringUtils.isNotBlank(activity.getWxItemBannerimg())) {
                Imgs img = imgsService.getPrimaryImg(activity.getId(), EnumList.ImgClsId.WxItemBannerimg.value);
                if (img == null) {
                    img = new Imgs();
                    img.setBsnsid(activity.getId());
                    img.setCreator(getUserName());
                    img.setCreatetime(new Date());
                    img.setOucode(activity.getOucode());
                    img.setIsdel(new BigDecimal(0));
                    img.setIsprimary(new BigDecimal(1));
                    img.setClsid(new BigDecimal(EnumList.ImgClsId.WxItemBannerimg.value));
                    img.setPicurl(activity.getWxItemBannerimg());
                    imgsService.insertSelective(img);
                } else {
                    img.setPicurl(activity.getWxItemBannerimg());
                    imgsService.updateByPrimaryKeySelective(img);
                }
            }
            if (StringUtils.isNotBlank(activity.getWxItemBackgroundimg())) {
                Imgs img = imgsService.getPrimaryImg(activity.getId(), EnumList.ImgClsId.WxItemBackgroundimg.value);
                if (img == null) {
                    img = new Imgs();
                    img.setBsnsid(activity.getId());
                    img.setCreator(getUserName());
                    img.setCreatetime(new Date());
                    img.setOucode(activity.getOucode());
                    img.setIsdel(new BigDecimal(0));
                    img.setIsprimary(new BigDecimal(1));
                    img.setClsid(new BigDecimal(EnumList.ImgClsId.WxItemBackgroundimg.value));
                    img.setPicurl(activity.getWxItemBackgroundimg());
                    imgsService.insertSelective(img);
                } else {
                    img.setPicurl(activity.getWxItemBackgroundimg());
                    imgsService.updateByPrimaryKeySelective(img);
                }
            }
            if (StringUtils.isNotBlank(activity.getWxItemBackgroundcolor())) {
                Imgs img = imgsService.getPrimaryImg(activity.getId(), EnumList.ImgClsId.WxItemBackgroundcolor.value);
                if (img == null) {
                    img = new Imgs();
                    img.setBsnsid(activity.getId());
                    img.setCreator(getUserName());
                    img.setCreatetime(new Date());
                    img.setOucode(activity.getOucode());
                    img.setIsdel(new BigDecimal(0));
                    img.setIsprimary(new BigDecimal(1));
                    img.setClsid(new BigDecimal(EnumList.ImgClsId.WxItemBackgroundcolor.value));
                    img.setPicurl(activity.getWxItemBackgroundcolor());
                    imgsService.insertSelective(img);
                } else {
                    img.setPicurl(activity.getWxItemBackgroundcolor());
                    imgsService.updateByPrimaryKeySelective(img);
                }
            }
            if (StringUtils.isNotBlank(activity.getWebItemListBackgroundcolor())) {
                Imgs img = imgsService.getPrimaryImg(activity.getId(), EnumList.ImgClsId.WebItemListBackgroundcolor.value);
                if (img == null) {
                    img = new Imgs();
                    img.setBsnsid(activity.getId());
                    img.setCreator(getUserName());
                    img.setCreatetime(new Date());
                    img.setOucode(activity.getOucode());
                    img.setIsdel(new BigDecimal(0));
                    img.setIsprimary(new BigDecimal(1));
                    img.setClsid(new BigDecimal(EnumList.ImgClsId.WebItemListBackgroundcolor.value));
                    img.setPicurl(activity.getWebItemListBackgroundcolor());
                    imgsService.insertSelective(img);
                } else {
                    img.setPicurl(activity.getWebItemListBackgroundcolor());
                    imgsService.updateByPrimaryKeySelective(img);
                }
            }
            if (StringUtils.isNotBlank(activity.getWxItemListBackgroundcolor())) {
                Imgs img = imgsService.getPrimaryImg(activity.getId(), EnumList.ImgClsId.WxItemListBackgroundcolor.value);
                if (img == null) {
                    img = new Imgs();
                    img.setBsnsid(activity.getId());
                    img.setCreator(getUserName());
                    img.setCreatetime(new Date());
                    img.setOucode(activity.getOucode());
                    img.setIsdel(new BigDecimal(0));
                    img.setIsprimary(new BigDecimal(1));
                    img.setClsid(new BigDecimal(EnumList.ImgClsId.WxItemListBackgroundcolor.value));
                    img.setPicurl(activity.getWxItemListBackgroundcolor());
                    imgsService.insertSelective(img);
                } else {
                    img.setPicurl(activity.getWxItemListBackgroundcolor());
                    imgsService.updateByPrimaryKeySelective(img);
                }
            }
            JedisManager.delObject(Global.INDEX_JIFENPRIZE);
        }
        return rmsg;
    }

    /**
     * 逻辑删除
     *
     * @param id
     * @return
     */
    @ResponseBody()
    @RequestMapping("deleteAct")
    public ResultMsg deleteAct(Integer id) {
        ResultMsg rmsg = new ResultMsg();
        int r = activityService.deleteLogicByID(id);
        if (r > 0) {
            rmsg.setResult(true);
            rmsg.setMsg("删除成功");
            JedisManager.delObject(Global.INDEX_JIFENPRIZE);

        } else {
            rmsg.setResult(false);
            rmsg.setMsg("删除失败");
        }
        return rmsg;

    }

    /**
     * 根据活动获取奖项列表
     *
     * @param actid
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "getActItemList", method = RequestMethod.GET)
    public ResultMsg getActItemList(Integer actid) {
        ResultMsg rmsg = new ResultMsg();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("actid", actid);
        List<Actitem> list = actItemService.getActItemList(map);
        rmsg.setResult(true);
        rmsg.setRows(list);
        return rmsg;
    }

    /**
     * 添加奖项信息
     *
     * @param actitem
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "addActItem", method = RequestMethod.POST)
    public ResultMsg addActItem(Actitem actitem) {
        ResultMsg rmsg = new ResultMsg();
        Activity activity = activityService.selectByPrimaryKey(actitem.getActid());
        if (activity.getType().equals(BigDecimal.valueOf(1))) {
            List<Actitem> list = actItemService.getActItemByActId(actitem.getActid());
            for (Actitem item : list) {
                if (item.getType().equals(actitem.getType())) {
                    rmsg.setResult(false);
                    rmsg.setMsg("该奖项已存在，不能重复添加");
                    return rmsg;
                }
            }
        }
        int r = actItemService.insertSelective(actitem);
        if (r > 0) {
            rmsg.setResult(true);
            rmsg.setMsg("添加成功");
            JedisManager.delObject(Global.INDEX_JIFENPRIZE);
        } else {
            rmsg.setResult(false);
            rmsg.setMsg("添加失败");
        }
        return rmsg;
    }

    /**
     * 删除奖项
     *
     * @param id
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "deleteActItem", method = RequestMethod.GET)
    public ResultMsg deleteActItem(Integer id) {
        ResultMsg rmsg = new ResultMsg();

        try {
            rmsg = actItemService.deleteLogic(id);
            JedisManager.delObject(Global.INDEX_JIFENPRIZE);
        } catch (Exception e) {
            logger.info("删除奖项失败:" + e.getMessage(), e);
            rmsg.setResult(false);
            rmsg.setMsg(e.getMessage());
        }

        return rmsg;
    }

    /**
     * 获取奖项列表
     *
     * @param actid 活动id
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "getActitemList", method = RequestMethod.GET)
    public ResultMsg getActitemList(Integer actid) {
        ResultMsg rmsg = new ResultMsg();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("actid", actid);
        map.put("isdel", 0);
        List<Actitem> list = actItemService.getActItemList(map);
        rmsg.setResult(true);
        rmsg.setRows(list);
        rmsg.setTotal(list.size());
        return rmsg;
    }

    /**
     * 编辑活动奖项
     *
     * @param actitem
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "editActitem", method = RequestMethod.POST)
    public ResultMsg editActitem(Actitem actitem) {
        ResultMsg rmsg = new ResultMsg();
        try {
            rmsg = actItemService.AddActitem(actitem);
            JedisManager.delObject(Global.INDEX_JIFENPRIZE);
        } catch (Exception e) {
            logger.info("编辑奖项失败:" + e.getMessage(), e);
            rmsg.setResult(false);
            rmsg.setMsg(e.getMessage());
        }
        return rmsg;
    }

    /**
     * 活动月抽奖记录
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "getMonthActList", method = RequestMethod.GET)
    public ResultMsg getMonthActList() {
        ResultMsg rmsg = new ResultMsg();
        Map<String, Object> map = new HashMap<String, Object>();
        if ("1".equals(getUserOuLevel())) {

        } else {
            map.put("oucode", getUserOuCode());
        }
        List<Activity> list = activityService.getMonthActList(map);
        for (Activity act : list) {
            act.setActitems(actItemService.getActItemByActId(act.getId()));
        }
        rmsg.setResult(true);
        rmsg.setRows(list);
        rmsg.setTotal(list.size());
        return rmsg;
    }

    /**
     * 开始月抽奖
     *
     * @param itemids
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "startAct", method = RequestMethod.GET)
    public ResultMsg startMonthAct(String itemids) {
        ResultMsg rmsg = new ResultMsg();
        try {
            rmsg = activityService.startAct(itemids);
        } catch (Exception ex) {
            ex.printStackTrace();
            rmsg.setResult(false);
            rmsg.setMsg(ex.getMessage());
        }
        return rmsg;
    }

    /**
     * 摇奖条件筛选
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "editFilter", method = RequestMethod.GET)
    public ResultMsg editFilter(Integer actid, Integer minpoints, Integer mincount, Integer filterlogic) {
        ResultMsg rmsg = new ResultMsg();
        if (actid == null) {
            rmsg.setResult(false);
            rmsg.setMsg("操作失败");
            return rmsg;
        }
        if (minpoints == null) {
            minpoints = 0;
        }
        if (mincount == null) {
            mincount = 0;
        }
        if (filterlogic == null) {
            filterlogic = 0;
        }
        int upd = activityService.editFilter(actid, minpoints, mincount, filterlogic);
        if (upd > 0) {
            rmsg.setResult(true);
            rmsg.setMsg("保存成功");
        } else {
            rmsg.setResult(false);
            rmsg.setMsg("保存失败");
        }

        return rmsg;
    }

    /**
     * 发布获奖名单
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "publishWinner", method = RequestMethod.GET)
    public ResultMsg publishWinner(Integer actid) {
        ResultMsg rmsg = new ResultMsg();
        try {
            rmsg = activityService.publishMonthWinner(actid);
        } catch (Exception ex) {
            ex.printStackTrace();
            rmsg.setResult(false);
            rmsg.setMsg(ex.getMessage());
        }
        return rmsg;
    }

    /**
     * 发布活动
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "publishAct", method = RequestMethod.GET)
    public ResultMsg publishAct(Integer actid) {
        ResultMsg rmsg = new ResultMsg();
        try {
            rmsg = activityService.publishAct(actid);
        } catch (Exception ex) {
            logger.error("发布活动失败异常" + ex.getMessage(), ex);
            rmsg.setResult(false);
            rmsg.setMsg("发布活动异常:" + ex.getMessage());
        }

        return rmsg;
    }

    /**
     * 结束活动
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "endAct", method = RequestMethod.GET)
    public ResultMsg endAct(Integer actid) {
        ResultMsg rmsg = new ResultMsg();
        try {
            rmsg = activityService.endAct(actid);
        } catch (Exception ex) {
            ex.printStackTrace();
            rmsg.setResult(false);
            rmsg.setMsg(ex.getMessage());
        }

        return rmsg;
    }

    /**
     * 获取获奖名单列表
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "getMonthActWinnerList", method = RequestMethod.GET)
    public ResultMsg getMonthActWinnerList(Integer actid) {
        ResultMsg rmsg = new ResultMsg();
        if (actid == null) {
            rmsg.setResult(false);
            rmsg.setMsg("活动不存在");
            return rmsg;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("actid", actid);
        PageInfo pageInfo = null;
        try {
            pageInfo = actOrderService.getMonthWinnerListPageList(map,getPageNum(),getPageSize());
        }catch (Exception e){
            logger.error("获取获奖名单列表错误"+e.getMessage(),e);
            e.printStackTrace();
        }
        return PageInfoResult.PageInfoMsg(pageInfo);
    }

    @RequestMapping(value = "exportMonthyWinners", method = RequestMethod.GET)
    public void exportMonthyWinners(Integer actid) {
        Activity activity = activityService.selectByPrimaryKey(BigDecimal.valueOf(actid));
        if (activity == null) {
            return;
        }

        String dateStr = DateUtil.formatDate("yyyy年MM月", activity.getStarttime());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("actid", actid);
        List<Actorder> list = actOrderService.getMonthWinnerList(map);

        String excelPath = "/Autowireds/doctemplate/tpl_monthWinners.xls";
        String root = request.getSession().getServletContext().getRealPath("/");
        String fileName = null;

        response.setCharacterEncoding("utf-8");
        try {
            response.setContentType("application/vnd.ms-excel; charset=ISO8859-1");
            InputStream is = new FileInputStream(root + excelPath);
            HSSFWorkbook wb = new HSSFWorkbook(is);
            HSSFSheet sheet = wb.getSheetAt(0);
            HSSFRow row = sheet.getRow(2);
            HSSFCell cell = row.getCell(0);
            sheet.getRow(0).getCell(0).setCellValue(dateStr + "月中奖名单");
            int flag = 0;
            for (Actorder ao : list) {
                HSSFRow newRow = sheet.createRow(2 + flag);
                for (int j = 0; j < 15; j++) {
                    newRow.createCell(j).setCellStyle(cell.getCellStyle());
                }
                int col = 0;
                newRow.getCell(col++).setCellValue(ao.getUserid());
                newRow.getCell(col++).setCellValue(ao.getRealname());
                newRow.getCell(col++).setCellValue(ao.getPhone());
                newRow.getCell(col++).setCellValue(ao.getCardno());
                String prizetypename = "";
                switch (ao.getPrizetype().intValue()) {
                    case 1:
                        prizetypename = "实体";
                        break;
                    case 2:
                        prizetypename = "虚拟";
                        break;
                    default:
                        break;
                }
                newRow.getCell(col++).setCellValue(prizetypename);
                newRow.getCell(col++).setCellValue(ao.getPrizename());
                newRow.getCell(col++).setCellValue(DateUtil.formatDate("yyyy-MM-dd", ao.getCreatetime()));
                newRow.getCell(col++).setCellValue(ao.getAreaname());
                newRow.getCell(col++).setCellValue(ao.getAddress());
                newRow.getCell(col++).setCellValue(ao.getZip());
                newRow.getCell(col++).setCellValue(ao.getExpress());
                newRow.getCell(col++).setCellValue(ao.getDeliveryno());
                newRow.getCell(col++).setCellValue(ao.getDeliverytime() != null ? DateUtil.formatDate("yyyy-MM-dd", ao.getDeliverytime()) : "");
                newRow.getCell(col++).setCellValue(ao.getState().intValue() > 1 ? "是" : "否");
                newRow.getCell(col++).setCellValue(ao.getRemark());
                flag++;
            }

            fileName = new String((dateStr + "月抽奖中奖名单").getBytes("gb2312"), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    fileName + DateUtil.formatDate("yyyyMMdd", DateUtil.getDate()) + ".xls");
            OutputStream ouputStream = response.getOutputStream();
            wb.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
            //poi3.9。没有close。。。
            // TODO: 2016/3/28
//            wb.close();
        } catch (Exception ex) {
            String opname = "月抽奖中奖名单";
            BufferedOutputStream bos = null;
            logger.error("导出" + opname + "异常:" + ex.getMessage(), ex);
            try {
                response.setContentType("text/plain");
                fileName = new String((opname + "导出失败").getBytes("gb2312"), "ISO8859-1");
                bos = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[2048];
                if (ex != null) {
                    buff = (ex.toString() + "==> 异常行号:" + ex.getStackTrace()[0].getLineNumber()).getBytes();
                }
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        fileName + DateUtil.formatDate("yyyyMMdd", DateUtil.getDate()) + ".txt");
                bos.write(buff);
                bos.flush();
                if (bos != null) {
                    bos.close();
                }
            } catch (Exception e) {
                logger.error("导出" + opname + "异常失败:" + e.getMessage(), e);
            }

        }
        return;
    }


    /**
     * 发货
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "deliverActOrder", method = RequestMethod.POST)
    public ResultMsg deliverActOrder(Integer id, String express, String deliveryno) {
        ResultMsg rmsg = new ResultMsg();
        Actorder actorder = actOrderService.selectByPrimaryKey(BigDecimal.valueOf(id));
        actorder.setDeliverytime(DateUtil.getDate());
        actorder.setHandler(getUserDetails().getUsername());
        actorder.setExpress(express);
        actorder.setDeliveryno(deliveryno);
        actorder.setState(BigDecimal.valueOf(3));
        try {
            int r = actOrderService.updateByPrimaryKeySelective(actorder);
            if (r > 0) {
                rmsg.setResult(true);
                rmsg.setMsg("发货处理成功");
            } else {
                rmsg.setResult(false);
                rmsg.setMsg("操作失败");
            }
        } catch (Exception ex) {
            logger.error("月抽奖发货异常,月抽奖活动订单ID："+id,ex);
            rmsg.setResult(false);
            rmsg.setMsg(ex.getMessage());
        }
        return rmsg;
    }

    /**
     * 修改收货地址
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "editAddress", method = RequestMethod.POST)
    public ResultMsg editAddress(Integer id, Integer provinceid, Integer cityid, Integer countyid, String address, String zip) {
        ResultMsg rmsg = new ResultMsg();
        String realname = request.getParameter("realname");
        String phone = request.getParameter("phone");
        Actorder actorder = actOrderService.selectByPrimaryKey(BigDecimal.valueOf(id));
        if(StringUtils.isNotBlank(realname)){ actorder.setRealname(realname);}
        if(StringUtils.isNotBlank(phone)){actorder.setPhone(phone);}
        actorder.setProvinceid(BigDecimal.valueOf(provinceid));
        actorder.setCityid(BigDecimal.valueOf(cityid));
        actorder.setCountyid(BigDecimal.valueOf(countyid));
        actorder.setAddress(address);
        actorder.setZip(zip);
        try {
            int upd = actOrderService.updateByPrimaryKeySelective(actorder);
            if (upd > 0) {
                rmsg.setResult(true);
                rmsg.setMsg("修改成功");
            } else {
                rmsg.setResult(false);
                rmsg.setMsg("修改失败");
            }
        } catch (Exception ex) {
            logger.error("月抽奖收货地址修改异常,月抽奖活动订单ID："+id,ex);
            rmsg.setResult(false);
            rmsg.setMsg(ex.getMessage());
        }
        return rmsg;
    }

    /**
     * 上传活动主题图、背景图
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "uploadActImg", method = RequestMethod.POST)
    public ResultMsg uploadActImg() {
        ResultMsg rmsg = new ResultMsg();
        String[] paths = {"activity"};
        List<String> list = FileUpload.Upload(request, paths);
        rmsg.setResult(true);
        rmsg.setMsg(list.get(list.size() - 1));
        try {
            JedisManager.delObject(Global.INDEX_JIFENPRIZE);
        } catch (Exception ex) {
            logger.error("清除缓存失败" + ex.getMessage(), ex);
        }
        return rmsg;
    }

}
